package api

import (
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"z-blog/e"
	"z-blog/jwt"
	"z-blog/models"
)

type auth struct {
	Username string `valid:"Required"`
	Password string `valid:"Required"`
}

// GetAuth @Summary 登录
// @Description 根据用户和密码登录，返回token
// @Tags auth
// @Produce json
// @Param username query string true "user name"
// @Param password query string true "password"
// @Router /get_auth [get]
func GetAuth(c *gin.Context) {
	username := c.Query("username")
	password := c.Query("password")

	valid := validation.Validation{}

	a := auth{
		Username: username,
		Password: password,
	}

	ok, _ := valid.Valid(&a)

	data := make(map[string]string)
	code := e.InvalidParams

	if ok {
		isExist := models.CheckAuth(username, password)
		if isExist {
			token, err := jwt.GenerateToken(username, password)
			if err != nil {
				code = e.ErrorAuthToken
			} else {
				data["token"] = token
				code = e.SUCCESS
			}
		} else {
			code = e.ErrorAuth
		}
	} else {
		for _, err := range valid.Errors {
			log.Println(err.Key, err.Message)
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}

// GetAuthInfo @Summary 获取用户信息
// @Description 根据用户姓名，获取用户信息列表
// @Produce  json
// @Tags auth
// @Param username query string true "用户姓名"
// @Param token query string true "token"
// @Router /auth/get_info [get]
func GetAuthInfo(c *gin.Context) {
	username := c.Query("username")

	maps := make(map[string]interface{})
	data := make(map[string]interface{})
	code := e.SUCCESS

	maps["username"] = username

	data["list"] = models.GetAuthInfo(maps)

	c.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  e.GetMsg(code),
		"data": data,
	})
}
